package com.corn.kafka.partition;

import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Properties;

/**
 * @author : Jim Wu
 * @version 1.0
 * @function :
 * @since : 2022/6/27 14:45
 */
@Slf4j
public class MyCustomerPartition {

    public static void main(String[] args) {
        Properties properties = new Properties();
        properties.put(ProducerConfig.PARTITIONER_CLASS_CONFIG, MyKafkaPartitioner.class.getName());
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "node1:9092,node2:9092");

        KafkaProducer<String, String> producer = new KafkaProducer(properties);
        String topic = "test_topic";
        // 一定是0
        ProducerRecord<String, String> commonMsg = new ProducerRecord<>(topic, "this is my test msg");
        producer.send(commonMsg, (metadata, ex) -> {
            int partition = metadata.partition();
            String sendTopic = metadata.topic();
            log.info("partition:{} , topic: {}", partition, sendTopic);
        });
        // 一定是1
        ProducerRecord<String, String> specialMsg = new ProducerRecord<>(topic, "this is my hahahahaha msg");
        producer.send(specialMsg, (metadata, ex) -> {
            int partition = metadata.partition();
            String sendTopic = metadata.topic();
            log.info("partition:{} , topic: {}", partition, sendTopic);
        });
        producer.close();
    }
}
